package com.example.baozidemo.aspect;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Component
@Aspect
public class RequestAspect {
    @Pointcut("execution( * com.example.baozidemo.*.*.*(..)))")
    //切入点说明:包下的任意类，任意方法，任意参数，任意返回值的方法都进行切入
    public void vegaAdmin() {

    }





    @Around("vegaAdmin()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();

            String requestUri = request.getRequestURI();// 得到请求的资源
            String method = request.getMethod();// 得到请求URL地址时使用的方法
            Object[] args = joinPoint.getArgs();
            String className = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();

            System.out.println("-----------------------------------请求方法和参数-----------------------------------");
            System.out.println("uri：" + requestUri + ",       method=：" + method + ",     className： "
                    + className + ", 参数：" + object2JsonString(args));
            System.out.println("-----------------------------------------------------------------------------------");
        }catch (Exception e){
            e.printStackTrace();
        }
        return joinPoint.proceed();
    }



    private String object2JsonString(Object[] object) {
        String jsonString = null;
        try {
            if (object != null && object.length > 0) {
                List newObj = new ArrayList<>();
                for (Object o : object) {
                    if (o instanceof HttpServletResponse) {
                    } else {
                        newObj.add(o);
                    }
                }
                jsonString = JSON.toJSONString(newObj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonString;
    }
}
